package com.itdachang.design.structural.flyweight;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 足道店:这相当于享元工厂
 *      店里面很多服务员
 *
 * 享元和原型
 * 1、原型返回的是克隆人
 * 2、享元是返回的是本人
 * @author gcq
 * @Create 2022-02-13
 */
public class ZuDao {

    /**
     * 池子
     */
    private static Map<String, AbstractWaitressFlyweight> pool = new HashMap<>();

    static {
        BeautifulWaitress waitress = new BeautifulWaitress("1111", "张三", 18);
        pool.put(waitress.id, waitress);
        BeautifulWaitress waitress2 = new BeautifulWaitress("2222", "李四", 20);
        pool.put(waitress2.id, waitress2);
    }

    /**
     * 添加服务员
     * @param abstractWaitressFlyweight
     */
    public void addWaitress(AbstractWaitressFlyweight abstractWaitressFlyweight) {
        pool.put(UUID.randomUUID().toString(), abstractWaitressFlyweight);
    }

    /**
     * 获取对应服务员，没有则随机返回一个
     * @param name
     * @return
     */
    public static AbstractWaitressFlyweight getWaitress(String name) {
        AbstractWaitressFlyweight flyweight = pool.get(name);
        if(flyweight == null) {
            // 随机获取一个
            for (AbstractWaitressFlyweight value : pool.values()) {
                // 当前共享对象是否能被获取
                /**
                 * 类似共享单车 别人在骑，你也不能骑他身上，必须等到其他人单车还了，你才能骑
                 */
                if(value.isCanService()) {
                    return value;
                }
            }
            return null;
        }
        return flyweight;
    }


}